<template>
  <q-card class="drag-tree-container w-[400px] bg-gray-50 rounded-lg shadow-lg">
    <!-- 搜索区域 -->
    <div class="p-4 bg-white border-b border-gray-200">
      <q-input
        v-model="searchTerm"
        dense
        outlined
        placeholder="搜索图层..."
        class="bg-white"
      >
        <template #prepend>
          <q-icon name="search" class="text-gray-500" />
        </template>
      </q-input>
    </div>

    <!-- 图层列表 -->
    <div class="layer-list overflow-auto h-[500px] p-2">
      <draggable
        v-model="filteredLayers"
        item-key="id"
        group="layers"
        handle=".drag-handle"
        :animation="200"
        @end="onDragEnd"
        class="space-y-2"
      >
        <template #item="{ element }">
          <layer-item
            :layer="element"
            @rename="handleRename"
            @toggle-visibility="toggleVisibility"
            @toggle-lock="toggleLock"
            @contextmenu="openContextMenu($event, element)"
          />
        </template>
      </draggable>
    </div>

    <!-- 右键菜单 -->
    <context-menu
      v-model:show="contextMenu.show"
      :position="contextMenu.position"
      :selected-layer="contextMenu.selectedLayer"
      @rename="handleRename"
      @copy="handleCopy"
      @paste="handlePaste"
    />
  </q-card>
</template>

<script setup lang="ts">
import { ref, computed, reactive } from "vue";
import draggable from "vuedraggable";
import LayerItem from "./LayerItem.vue";
import ContextMenu from "./ContextMenu.vue";

// 图层类型定义
type LayerType = "container" | "component" | "shape" | "text" | "chart";

interface Layer {
  id: string;
  name: string;
  type: LayerType;
  visible: boolean;
  locked: boolean;
  children?: Layer[];
}

// 模拟数据
const layers = ref<Layer[]>([
  {
    id: "1",
    name: "容器1",
    type: "container",
    visible: true,
    locked: false,
    children: [
      {
        id: "1-1",
        name: "文本1",
        type: "text",
        visible: true,
        locked: false,
      },
      {
        id: "1-2",
        name: "形状1",
        type: "shape",
        visible: true,
        locked: false,
      },
    ],
  },
  {
    id: "2",
    name: "组件1",
    type: "component",
    visible: true,
    locked: false,
  },
  {
    id: "3",
    name: "图表1",
    type: "chart",
    visible: true,
    locked: true,
  },
]);

// 搜索功能
const searchTerm = ref("");
const filteredLayers = computed(() => {
  if (!searchTerm.value) return layers.value;
  return filterLayers(layers.value, searchTerm.value.toLowerCase());
});

function filterLayers(layers: Layer[], term: string): Layer[] {
  return layers
    .map((layer) => {
      const newLayer = { ...layer };
      if (layer.children) {
        newLayer.children = filterLayers(layer.children, term);
      }
      return newLayer;
    })
    .filter(
      (layer) =>
        layer.name.toLowerCase().includes(term) ||
        (layer.children && layer.children.length > 0)
    );
}

// 拖拽功能
function onDragEnd(event: any) {
  console.log("拖拽完成", event);
}

// 右键菜单功能
const contextMenu = reactive({
  show: false,
  position: { x: 0, y: 0 },
  selectedLayer: null as Layer | null,
});

function openContextMenu(event: MouseEvent, layer: Layer) {
  event.preventDefault();
  contextMenu.show = true;
  contextMenu.position = { x: event.clientX, y: event.clientY };
  contextMenu.selectedLayer = layer;
}

// 图层操作
function toggleVisibility(layerId: string) {
  const layer = findLayer(layers.value, layerId);
  if (layer) layer.visible = !layer.visible;
}

function toggleLock(layerId: string) {
  const layer = findLayer(layers.value, layerId);
  if (layer) layer.locked = !layer.locked;
}

function handleRename(layerId: string, newName: string) {
  const layer = findLayer(layers.value, layerId);
  if (layer) layer.name = newName;
}

function findLayer(layers: Layer[], id: string): Layer | null {
  for (const layer of layers) {
    if (layer.id === id) return layer;
    if (layer.children) {
      const found = findLayer(layer.children, id);
      if (found) return found;
    }
  }
  return null;
}

// 复制粘贴功能
const clipboard = ref<Layer[]>([]);

function handleCopy(layer: Layer) {
  clipboard.value = [deepClone(layer)];
}

function handlePaste(targetLayer: Layer) {
  if (!clipboard.value.length) return;

  const newLayers = clipboard.value.map((layer) => ({
    ...deepClone(layer),
    id: generateId(),
    name: layer.name + " - 副本",
  }));

  // 查找目标图层所在的位置并插入
  const insertLayer = (list: Layer[]) => {
    const index = list.findIndex((l) => l.id === targetLayer.id);
    if (index !== -1) {
      list.splice(index, 0, ...newLayers);
      return true;
    }

    for (const layer of list) {
      if (layer.children) {
        if (insertLayer(layer.children)) return true;
      }
    }
    return false;
  };

  insertLayer(layers.value);
}

function deepClone(obj: any): any {
  return JSON.parse(JSON.stringify(obj));
}

function generateId(): string {
  return "layer-" + Date.now() + "-" + Math.floor(Math.random() * 1000);
}
</script>
